package com.beisita.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 同时有配置的类和注解方式的话，filter顺序：首先是用配置文件配置的Filter（按照Order顺序），然后是WebFilter注解配置的。
 */
@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"}, initParams = {@WebInitParam(name = "loginUI", value = "/home/loginUI"), @WebInitParam(name = "loginProcess", value = "home/login"), @WebInitParam(name = "encoding", value = "utf-8")})
public class LoginFilter implements Filter {
    private FilterConfig config;

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        String loginUI = this.config.getInitParameter("loginUI");
        String loginProcess = this.config.getInitParameter("loginProcess");
        String encoding = this.config.getInitParameter("encoding");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        request.setCharacterEncoding(encoding);
        String uri = request.getRequestURI();
        if (uri.contains(loginUI) || uri.contains(loginProcess)) {
            chain.doFilter((ServletRequest) request, (ServletResponse) response);
        } else {
            chain.doFilter((ServletRequest) request, (ServletResponse) response);
        }
    }

    public void destroy() {
        this.config = null;
    }
}
